package com.itwenke.springbootdemo.shirojdbc;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

public class Demo {

    @Test
    public void authen(){
        // 创建 JdbcRealm
        JdbcRealm jdbcRealm = new JdbcRealm();
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///shiro-jdbc");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        jdbcRealm.setDataSource(dataSource);

        // 开启权限校验
        jdbcRealm.setPermissionsLookupEnabled(true);

        // 创建 DefaultSecurityManager
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        // DefaultSecurityManager 与 SimpleAccountRealm 建立连接
        securityManager.setRealm(jdbcRealm);

        // Subject 和 DefaultSecurityManager 建立关系
        SecurityUtils.setSecurityManager(securityManager);

        // 获取 Subject
        Subject subject = SecurityUtils.getSubject();

        // 发起认证
        subject.login(new UsernamePasswordToken("admin", "admin"));

        // 判断是否认证成功
        System.out.println("是否认证成功：" + subject.isAuthenticated());

        // 角色校验
        System.out.println("是否拥有超级管理员角色：" + subject.hasRole("超级管理员"));

        // 权限校验
        System.out.println("是否拥有添加用户权限：" + subject.isPermitted("user:add"));
    }
}
